package com.vrv.netmgr.assets.chart;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.UrlPrefix;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.netmgr.R;

/**
 * 本地设备资源统计
 * 
 * @author gaopei
 * 
 */
@SuppressLint("HandlerLeak")
public class DeviceResStatActivity extends Activity {

	/** 为统计图开辟的区域 */
	private LinearLayout layout;
	List<String> listLabel = new ArrayList<String>();
	List<Long> listVal = new ArrayList<Long>();
	/** 饼形图 */
	GraphicalView pieChartView = null;
	CategorySeries dataset;
	DefaultRenderer renderer;
	/**
	 * 等待对话框
	 */
	private ProgressDialog progressDialog;
	/**
	 * 查询
	 */
	private static final int QUERY_OS = 1;
	private static final int QUERY_SYS_MEMORY = 2;
	private static final int QUERY_CPU_MAIN_FREQUENCY = 3;
	private static final int QUERY_CPU_TYPE = 4;
	private static final int QUERY_HARD_DISK_STORAGE = 5;
	private static final int NET_ERR = 99;
	private String chartTitle;

	// PopWindow检索条件相关
	private ImageButton moreFuncBtn;
	private PopupWindow pwMyPopWindow;
	private ListView lvPopupList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.alarm_region_statistics_layout);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tools_title);
		initView();
		progressDialog = ProgressDialog.show(DeviceResStatActivity.this, "", "查询中...", true, true);

		new Thread(new Runnable() {
			@Override
			public void run() {
				getDataFromServer(QUERY_OS);
				handler.sendEmptyMessage(QUERY_OS);
			}
		}).start();
	}

	/**
	 * 处理器
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY_OS:
				buildPieChartView();
				break;
			case NET_ERR:
				Toast.makeText(DeviceResStatActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
				break;
			}
		}
	};

	private void initView() {
		TextView titleView = (TextView) findViewById(R.id.title_text);
		titleView.setText("本地设备资源统计");

		// 返回按钮
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setVisibility(View.VISIBLE);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		// 初始化chart的渲染位置
		layout = (LinearLayout) findViewById(R.id.bar_chart);
		iniPopupWindow();
		// 更多操作按钮
		moreFuncBtn = (ImageButton) findViewById(R.id.moreFunctionBtn);
		moreFuncBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pwMyPopWindow.isShowing()) {
					pwMyPopWindow.dismiss();// 关闭
				} else {
					pwMyPopWindow.showAsDropDown(moreFuncBtn);// 显示
				}
			}
		});
	}

	private void iniPopupWindow() {
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.title_func_popupwindow, null);
		lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
		pwMyPopWindow = new PopupWindow(layout);
		pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件

		String[] arr = getResources().getStringArray(R.array.deviceResStatType);
		if (null == itemDatas) {
			itemDatas = new ArrayList();
		} else {
			itemDatas.clear();
		}
		for (int i = 0; i < arr.length; i++) {
			PopItem item = new PopItem();
			item.title = arr[i];
			item.check = false;
			if (0 == i) {
				item.check = true;
			}
			itemDatas.add(item);
		}
		if (null == pAdapter) {
			pAdapter = new PopWindowAdapter(itemDatas, DeviceResStatActivity.this);
		}
		lvPopupList.setAdapter(pAdapter);
		lvPopupList.setOnItemClickListener(new ClickPopupItemListener());

		// 控制popupwindow的宽度和高度自适应
		lvPopupList.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
		pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
		// pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight()) * 3);
		pwMyPopWindow.setHeight(LayoutParams.WRAP_CONTENT);

		// 控制popupwindow点击屏幕其他地方消失
		pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg_popupwindow));
		// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
		pwMyPopWindow.setOutsideTouchable(true);
	}

	private class ClickPopupItemListener implements AdapterView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
			pwMyPopWindow.dismiss();
			progressDialog = ProgressDialog.show(DeviceResStatActivity.this, "", "查询中...", true, true);
			new Thread(new Runnable() {
				@Override
				public void run() {
					int temp = 0;
					switch (position) {
					case QUERY_OS - 1:
						temp = QUERY_OS;
						break;
					case QUERY_SYS_MEMORY - 1:
						temp = QUERY_SYS_MEMORY;
						break;
					case QUERY_CPU_MAIN_FREQUENCY - 1:
						temp = QUERY_CPU_MAIN_FREQUENCY;
						break;
					case QUERY_CPU_TYPE - 1:
						temp = QUERY_CPU_TYPE;
						break;
					case QUERY_HARD_DISK_STORAGE - 1:
						temp = QUERY_HARD_DISK_STORAGE;
						break;
					}
					getDataFromServer(temp);
					handler.sendEmptyMessage(QUERY_OS);
				}
			}).start();

			for (int i = 0; i < itemDatas.size(); i++) {
				if (position == i) {
					itemDatas.get(i).check = true;
				} else {
					itemDatas.get(i).check = false;
				}
			}
			pAdapter.notifyDataSetChanged();
			// Toast.makeText(DeviceResStatActivity.this, "" +
			// itemDatas.get(position).title, Toast.LENGTH_LONG).show();
		}
	}

	public List<PopItem> itemDatas;
	public PopWindowAdapter pAdapter;

	public class PopWindowAdapter extends BaseAdapter {
		public List<PopItem> lst;
		public Context mContext;

		public PopWindowAdapter(List<PopItem> lst, Context context) {
			this.lst = lst;
			this.mContext = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return lst.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return lst.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(DeviceResStatActivity.this).inflate(R.layout.list_item_popupwindow, null);
			}
			CheckBox cBox = (CheckBox) convertView.findViewById(R.id.check);
			TextView title = (TextView) convertView.findViewById(R.id.tv_list_item);

			cBox.setChecked(lst.get(position).check);
			title.setText(lst.get(position).title);

			return convertView;
		}

	}

	public class PopItem {
		public String title;
		public boolean check = false;
	}

	public void buildPieChartView() {// String[] labels,Object[] vals) {
		/** 统计图所需数据 */
		int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.YELLOW, Color.RED, getResources().getColor(R.color.darkblue), getResources().getColor(R.color.brown),
		        getResources().getColor(R.color.orange), getResources().getColor(R.color.purple), getResources().getColor(R.color.darkorchid) };
		Object[] labels = listLabel.toArray();
		Object[] vals = listVal.toArray();
		renderer = buildCategoryRenderer(colors);
		renderer.setZoomButtonsVisible(false);
		renderer.setShowLegend(false);
		renderer.setZoomEnabled(true);
		renderer.setChartTitle(chartTitle);
		renderer.setChartTitleTextSize(25);
		// renderer.setDisplayValues(true);
		renderer.setLabelsColor(Color.BLACK);
		renderer.setShowLabels(true);
		renderer.setClickEnabled(true);
		dataset = buildCategoryDataset("", labels, vals);
		if (pieChartView != null)
			layout.removeView(pieChartView);
		pieChartView = ChartFactory.getPieChartView(this, dataset, renderer);
		layout.addView(pieChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		pieChartView.setOnClickListener(new MyClickListener());
	}

	private class MyClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			SeriesSelection seriesSelection = pieChartView.getCurrentSeriesAndPoint();
			if (seriesSelection != null) {
				for (int i = 0; i < dataset.getItemCount(); i++) {
					renderer.getSeriesRendererAt(i).setHighlighted(i == seriesSelection.getPointIndex());
				}
				pieChartView.repaint();
				// Toast.makeText(
				// DeviceResStatActivity.this,
				// "Chart data point index "
				// + seriesSelection.getPointIndex() + " selected"
				// + " point value=" + seriesSelection.getValue(),
				// Toast.LENGTH_SHORT).show();
			}
		}

	}

	public CategorySeries buildCategoryDataset(String title, Object[] labels, Object[] values) {
		CategorySeries series = new CategorySeries(title);
		int k = 0;
		for (Object value : values) {
			series.add((String) labels[k++], (Long) value);
		}
		return series;
	}

	public DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		renderer.setLabelsTextSize(20);
		renderer.setLegendTextSize(20);
		renderer.setMargins(new int[] { 0, 30, 15, 0 });
		for (int i = 0; i < listLabel.size(); i++) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(colors[i]);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	// 查询所有数据
	public void getDataFromServer(int statisticsType) {
		Map<String, String> map = new HashMap<String, String>();
		boolean retVal = qryRegisterStat(map, statisticsType);
		if (!retVal)
			handler.sendEmptyMessage(NET_ERR);
	}

	public boolean qryRegisterStat(Map<String, String> map, int statisticsType) {
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext()).getUrlPrefix();
		String urlTailString = null;
		switch (statisticsType) {
		case QUERY_OS:
			urlTailString = "/deviceInfo/getDeviceResourceByOSType.do";
			chartTitle = "按操作系统统计";
			break;
		case QUERY_SYS_MEMORY:
			urlTailString = "/deviceInfo/getDeviceResourceByMemery.do";
			chartTitle = "按系统内存统计";
			break;
		case QUERY_CPU_MAIN_FREQUENCY:
			urlTailString = "/deviceInfo/getDeviceResourceByCPUFrequency.do";
			chartTitle = "按CPU主频(HZ)统计";
			break;
		case QUERY_CPU_TYPE:
			urlTailString = "/deviceInfo/getDeviceResourceByCPUType.do";
			chartTitle = "按CPU类型统计";
			break;
		case QUERY_HARD_DISK_STORAGE:
			urlTailString = "/deviceInfo/getDeviceResourceByDiskSize.do";
			chartTitle = "按硬盘存储量统计";
			break;
		}
		String urlAddr = urlPrefix + urlTailString;
		String response = httpClientToServer.doPost(urlAddr, map);
		if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");
			if (!retVal)
				return retVal;
			int count = jsonObj.getInt("totalRecords");
			if (count < 1)
				return retVal;
			JSONArray jArr = jsonObj.getJSONArray("records");
			listLabel.clear();
			listVal.clear();
			for (int i = 0; i < jArr.length(); i++) {
				JSONObject jObj = (JSONObject) jArr.opt(i);
				listLabel.add(jObj.getString("type") + " 共" + jObj.getLong("Num") + "台 ： " + jObj.getDouble("persent") + "%");
				listVal.add(jObj.getLong("Num"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return retVal;
	}

	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
		super.onBackPressed();
	}
}
